package com.park.service.impl.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSONObject;
import com.park.client.model.user.UserModel;
import com.park.common.constant.Constant;

@Service
public class MessageHandler implements WebSocketHandler{
    private  static final Log log=LogFactory.getLog(MessageHandler.class);

  //在线用户
	private  static final Map<String,WebSocketSession> userMap = new HashMap<>();
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		String userName=this.getUserName(session);
        if(userMap.get(userName) != null){
            userMap.remove(userName);
        }
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String userName=this.getUserName(session);
        if(userName != null && userMap.get(userName) == null){
            userMap.put(userName, session);
        }
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		 session.sendMessage(message);  
	     log.info("Websocket：handleMessage send message："+message);
	}

	@Override
	public void handleTransportError(WebSocketSession arg0, Throwable error) throws Exception {
		log.error("Websocket：handleMessage send message："+error);
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	
	/**
	 * 发送给指定用户
	 */
	public void sendMessageToUser(String userName, String msg) {
		try {  
		  	TextMessage message = new TextMessage(msg);
	        WebSocketSession session = userMap.get(userName);  
	        if(session !=null && session.isOpen()) {  
	               session.sendMessage(message);  
	        }
		} catch (IOException e) {  
			log.error("发送消息失败:", e);
		}  
	  }

	/**
	 * 所有在线用户
	 */
	  public void sendMessageToUsers(String message) {
	        Set<String> userNameList = userMap.keySet();  
	        for(String userName: userNameList) {  
	            this.sendMessageToUser(userName, message);  
	        }  
	    }
	  
	  public String getUserName(WebSocketSession session){  
	        Object object = session.getAttributes().values().toArray()[0];
	        if(object instanceof UserModel){
	        	UserModel user = (UserModel)object;
	        	return user.getUsername();
	        }
	         return Constant.TOURIST_CODE;//游客
	    }

	  /**
	   * 所有用户
	   */
	public void sendMessage(Object object) {
		try {
			String jsonObject = JSONObject.toJSONString(object);
			Set<String> userNameList = userMap.keySet();  
		    for(String userName: userNameList) {  
		          this.sendMessageToUser(userName, jsonObject);  
		    }  
		} catch (Exception e) {
			log.error("发送消息失败:", e);
		}
	} 
}
